<?php

/**
 * Single attachment file of an email.
 *
 * @author tobias.vogel
 */
class Db_Attachments extends Common {

	protected static $tableName = TAB_ATTACHMENTS;
	protected static $dbFields = array(
		'id',
		'att_checksum',
		'att_name',
		'att_contenttype',
		'att_mimetype',
		'deleted'
	);

	/**
	 * @var Db_Attachments
	 */
	public $objectArray;
	public $id;
	public $att_checksum;
	public $att_name;
	public $att_contenttype;
	public $att_mimetype;
	public $deleted;

	function __construct($value = NULL, $fieldName = NULL) {
		parent::__construct($value, $fieldName);
	}

	/**
	 * Assigns an attachment to an email
	 * 
	 * @param Db_Mail $mail 
	 */
	public function assignToMail($mail) {
		// replace into, as attachments may be contained multiple times in one email
		$sql = 'REPLACE INTO ?f VALUES(?d, ?d);';
		self::$DB->q($sql, TAB_MAILS_ATTACHMENTS, $mail->id, $this->id);
	}

	/**
	 * Gets the attachment directory for this attachment. If it doesn't exist,
	 * it will be created automatically.
	 * 
	 * @return string Directory, where the attachments are stored
	 * @throws RuntimeException If mail has not been saved yet
	 */
	public function getAttachmentDir() {

		if ($this->att_checksum === null) {
			throw new Mailfetcher_Exception('Attachment has no checksum, directory can not be determined.');
		}
		
		$segmentSubdir = Config::get('MAIL_PATH') . substr($this->att_checksum, 0, 2);
		if (!file_exists($segmentSubdir)) {
			mkdir($segmentSubdir);
		}
		return $segmentSubdir;
	}

	/**
	 * Gets the filename of the attachment on the disk.
	 * 
	 * @return string The filename with full path on the disk 
	 */
	public function getDiskFileName() {
//		$ext = pathinfo($this->att_name, PATHINFO_EXTENSION);
		return $this->getAttachmentDir() . DS . $this->att_checksum;
	}

}
